/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.zhixun.mobile.modules.base.web;

import java.beans.PropertyEditorSupport;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.boxin.ims.modules.wechat.entity.JiuWechatMember;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;

/**
 * ������֧����
 * @author ThinkGem
 * @version 2013-3-23
 */
public abstract class BaseController {
	
	
	/**
	 * ��֤Beanʵ������
	 */
	@Autowired
	protected Validator validator;

	/**
	 * ����˲�����Ч����֤
	 * @param object ��֤��ʵ�����
	 * @param groups ��֤��
	 * @return ��֤�ɹ�������true������ʧ�ܣ���������Ϣ��ӵ� message ��
	 */
	protected boolean beanValidator(Model model, Object object, Class<?>... groups) {
//		try{
//			BeanValidators.validateWithException(validator, object, groups);
//		}catch(ConstraintViolationException ex){
//			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
//			list.add(0, "������֤ʧ�ܣ�");
//			addMessage(model, list.toArray(new String[]{}));
//			return false;
//		}
		return true;
	}
	
	public String didplayYesOrNo(String key){
		return (key==null || "0".equals(key)) ?"��" : "��";
	}
	
	/**
	 * ����˲�����Ч����֤
	 * @param object ��֤��ʵ�����
	 * @param groups ��֤��
	 * @return ��֤�ɹ�������true������ʧ�ܣ���������Ϣ��ӵ� flash message ��
	 */
	protected boolean beanValidator(RedirectAttributes redirectAttributes, Object object, Class<?>... groups) {
//		try{
//			BeanValidators.validateWithException(validator, object, groups);
//		}catch(ConstraintViolationException ex){
//			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
//			list.add(0, "������֤ʧ�ܣ�");
//			addMessage(redirectAttributes, list.toArray(new String[]{}));
//			return false;
//		}
		return true;
	}
	
	/**
	 * ���Model��Ϣ
	 * @param message
	 */
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		model.addAttribute("message", sb.toString());
	}
	
	/**
	 * ���Flash��Ϣ
	 * @param message
	 */
	protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}
	
	/**
	 * ��ʼ�����ݰ�
	 * 1. �����д��ݽ�����String����HTML���룬��ֹXSS����
	 * 2. ���ֶ���Date����ת��ΪString����
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String����ת���������д��ݽ�����String����HTML���룬��ֹXSS����
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
		// Date ����ת��
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				//setValue(DateUtils.parseDate(text));
			}
		});
	}
	
	
	
	public void responseJson( HttpServletRequest request, HttpServletResponse response,Object object){
//		response.setContentType("application/json;charset=utf-8"); 
//        response.setHeader("Cache-Control", "no-cache");
//        response.setCharacterEncoding("utf-8");
//		try {
//			PrintWriter out = response.getWriter();
//			String jsonString = JsonMapper.getInstance().toJson(object);
//			out.print( jsonString );
//			out.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}
	protected void writeMessageAndRedirect(HttpServletRequest request,HttpServletResponse response,String message,String redirectUrl) {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://" + request.getServerName() + path;
			
			out = response.getWriter();
			out.print("<script type=\"text/javascript\">alert('"+message+"');location.href='"+basePath + redirectUrl+"';</script>");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(null != out) {
				out.flush();
				out.close();
			}
		}
	}
	public void writeJson( HttpServletRequest request, HttpServletResponse response,Object object){
		response.setContentType("application/json; charset=UTF-8");
		try {
			PrintWriter out = response.getWriter();
			String jsonString = JSON.toJSON(object).toString();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	public void responseXML( HttpServletRequest request, HttpServletResponse response,String xml){
		response.setContentType("application/xml; charset=UTF-8");
		try {
			
			PrintWriter out = response.getWriter();
			out.write(xml);
			out.flush();
			out.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	
	protected String getOpenId(String cookieName,HttpServletRequest request){
		String openId = CookieUtils.getCookie(request, cookieName);
		request.setAttribute("random", getRandom());
		return openId;
	}
	/**
	 * 随机数
	 * @return
	 */
	private String getRandom(){
		Random rand = new Random();
		int randNumberA = rand.nextInt(100);
		int randNumberB = rand.nextInt(10);
		return DateUtils.getDateTimeString() + randNumberA + randNumberB;
	}

}
